<template>
    <div style="margin-top: 10px">
        <div class="editButton">
            <a-button-group>
                <a-button @click="addDefaultButton()" type="primary">
                    {{i18n('isButton.addDefault','添加默认')}}
                </a-button>
                <a-button @click="addButton()"><i class="iconfont iconadd"></i></a-button>
                <a-button @click="deleteButton()"><i class="iconfont icontrash"></i></a-button>
                <a-button @click="moveBtnUp()"><i class="iconfont iconshang"></i></a-button>
                <a-button @click="moveBtnDown()"><i class="iconfont iconxia"></i></a-button>
            </a-button-group>
        </div>
        <div style="margin-top: 10px">
            <a-table ref="table"
                     :allowRowSelect="true"
                     :multiSelect="true"
                     :columns="buttonColumns"
                     :dataSource="buttonDef"
                     :pagination="false"
                     :rowSelection="{ onChange: onButtonSelectChange}"
                     rowKey="idx_"
                     :bordered="true"
                     :showPage="false">
                    <span slot="name" slot-scope="text, record">
                        <a-input v-model="record.name" @change="updateI18nName(record,'name')">
              <my-icon slot="addonAfter" type="iconearth-full" @click="editI18nName(record,'name')"/>
          </a-input>
                    </span>
                    <span slot="type" slot-scope="text, record">
                       <a-select
                           v-model="record.type"
                           :options="btnTypeOptions" style="width: 100px;" :dropdown-menu-style="{width:'100px'}"
                           :dropdownMatchSelectWidth="false"
                           @change="changeBtnType(record)" >

                       </a-select>
                    </span>
                    <span slot="method" slot-scope="text, record">
                        <a-input :disabled="record.isPreDef" v-model="record.method" />
                    </span>
                    <span slot="setting" slot-scope="text, record">
                        <a-button v-if="record.needConfig" @click="handleConfig(record)" >
                            {{$ti18('rxList.config','配置')}}
                        </a-button>
                    </span>
                    <template slot="conditionConfig" slot-scope="text,record,index">
                        <span style="margin-right: 10px" :style="'color:'+(record.conditionConfig && record.conditionConfig!='{}'?'green':'red')">{{record.conditionConfig && record.conditionConfig!='{}'?'已配置':'未配置'}}</span>
                        <a-button @click="configDef(record)">
                            {{$ti18('rxList.config','配置')}}
                        </a-button>
                    </template>
                    <template slot="preCondConfig" slot-scope="text,record,index">
                        <span style="margin-right: 10px" :style="'color:'+(record.preCondConfig && record.preCondConfig!='{}'?'green':'red')">{{record.preCondConfig && record.preCondConfig!='{}'?'已配置':'未配置'}}</span>
                        <a-button @click="configPreDef(record)">
                            {{$ti18('rxList.config','配置')}}
                        </a-button>
                    </template>
            </a-table>
        </div>
    </div>
</template>

<script>
import {Util, GridMixin, Dialog,I18Parse} from "@lowcode/jpaas-common-lib"
import FormMobileSetting from './FormMobileSetting'
import FormSolutionButtonPreMappingConfig from "@/views/modules/form/core/FormSolutionButtonPreMappingConfig";
import type from "@/components/Exception/type";
import FormSolutionButtonMappingConfig from "@/views/modules/form/core/FormSolutionButtonMappingConfig";


export default {
    name:"form-mobile-buttons",
    mixins:[GridMixin],
    props:{
        buttonDef:{
            type:Array
        },
        boEnt:{
            type:Object
        },
        bodefId:{
            type:String
        },
    },
    data(){
        return{

            //按钮列
            buttonColumns:[
                {title: this.$ti18('rxForm.name','名称'),dataIndex: 'name',allowCellEdit:true, scopedSlots: { customRender: 'name' }},
                {title: this.$ti18('rxForm.type','类型'),dataIndex: 'type',allowCellEdit:true,scopedSlots: { customRender: 'type' }},
                {title: this.i18n('form.buttonMethod','按钮方法'),dataIndex: 'method',allowCellEdit:true,scopedSlots: { customRender: 'method' }},
                {title: this.$ti18('rxList.config','配置'),dataIndex: 'setting',scopedSlots: { customRender: 'setting' }},
                {title: this.i18n('form.config','条件配置'), dataIndex: 'conditionConfig', scopedSlots: {customRender: 'conditionConfig'}},
                {title: this.i18n('form.preCondConfig','前置条件'), dataIndex: 'preCondConfig', scopedSlots: {customRender: 'preCondConfig'}}
            ],
            //默认按钮
            defaultButtons:[{
                name:this.i18n('form.startFlow','启动流程'),
                isPreDef:true,
                type:"startFlow",
                method:"startFlow",
                setting:"",
                needConfig: false,
                conditionConfig:'',
                preCondConfig:'',

            },{
                name:this.$ti18('rxForm.saveBtn','保存'),
                isPreDef:true,
                type:"save",
                method:"save",
                setting:"",
                needConfig:false,
                conditionConfig:'',
                preCondConfig:'',
            }],
            buttonSelectedRowKeys:[],
            buttonSelectedRows:[],
            //按钮类型
            buttonTypes:[
                {name:this.$ti18('rxForm.saveBtn','保存'),type:"save",method:"save",needConfig:false,isPreDef:true},
                {name:this.i18n('form.startFlow','启动流程'),type:"startFlow",method:"startFlow",needConfig:false,isPreDef:true},
                {name:this.i18n('form.custom','自定义'),type:"custom",method:"",needConfig:false,isPreDef:false},
                {name:this.i18n('form.openCustomForm','打开表单'),type:"openForm",method:"openForm", needConfig:true,isPreDef:true}],
            defaultBtnI18ns:{
                "save":{
                    "zh-CN":"保存",
                    "en-US":"save",
                    "ja-JP":""
                },
                "startFlow":{
                    "zh-CN": "启动流程",
                    "en-US":"Start Flow",
                    "ja-JP": ""
                }
            }
        }

    },
    created(){
        this.getCurrentI18n();
        this.setI18nBtnVal();
    },
    computed:{
        btnTypeOptions(){
            let types=this.buttonTypes.map(item=>{
                return {value:item.type,label:item.name};
            })
            return types;
        }
    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"formMobile",key);
        },
        setI18nBtnVal(){
            if(!this.buttonDef || this.buttonDef.length==0){
                return;
            }
            let self_=this;
            this.buttonDef.forEach(btn => {
                self_.loadInitBtnI18nVal(btn,'name');
            });
        },
        configPreDef(row){
            if (!this.bodefId) {
                this.$message.warning(this.$ti18('rxForm.formName','请选择表单！','','select'));
                return;
            }
            var conf= {
                curVm:this,
                data:{config:row.preCondConfig,boDefId:this.bodefId},
                widthHeight:['1000px', '700px'],
                component:FormSolutionButtonPreMappingConfig,
                title:this.i18n('isButton.buttonPreconditions','按钮前置条件')
            };
            var self_=this;
            Util.open(conf,function(action,data){
                if(action!='ok')return;
                row.preCondConfig=data;
                self_.$refs.table.$forceUpdate();
            })
        },
        configDef(row){
            if (!this.bodefId) {
                this.$message.warning(this.$ti18('rxForm.formName',"请选择表单！",'','select'));
                return;
            }
            var conf= {
                curVm:this,
                data:{config:row.conditionConfig,boDefId:this.bodefId},
                widthHeight:['1000px', '700px'],
                component:FormSolutionButtonMappingConfig,
                title:this.i18n('isButton.buttonConditionConfiguration','按钮条件配置')
            };
            var self_=this;
            Util.open(conf,function(action,data){
                if(action!='ok')return;
                row.conditionConfig=data;
                self_.$refs.table.$forceUpdate();
            })
        },
        //添加默认按钮
        addDefaultButton(){
            for(let btn of this.defaultButtons){
                this.loadInitBtnI18nVal(btn,'name');
                this.setOtherDefaultI18nVal(btn);
                let exist=this.isExists(btn.method);
                if(exist){
                    //给已存在的按钮添加上多语言字段
                    for (let button of this.buttonDef){
                        if (button.method==btn.method){
                            button.langJsonVal=btn.langJsonVal
                        }
                    }
                    continue;
                }
                btn.idx_=Util.randomId();
                this.buttonDef.push(btn);
            }
        },
        //设置中文、英文默认值
        setOtherDefaultI18nVal(btn){
            let langs=I18Parse.handleLanList();
            if(!langs || langs.length==0){
                return;
            }
            let self_=this;
            langs.forEach(lang=>{
                if(lang!=this.i18nCurrent){
                    let langVal=self_.defaultBtnI18ns[btn.method];
                    if(langVal){
                        let i18nJson= JSON.parse(btn.langJsonVal);
                        i18nJson[lang]=langVal[lang];
                        btn.langJsonVal=JSON.stringify(i18nJson);
                    }
                }
            })

        },
        //判断按钮是否存在。
        isExists(method){
            if(this.buttonDef !=undefined){
                for(let btn of this.buttonDef){
                    if(btn.method==method){
                        return true;
                    }
                }
            }
            return false;
        },
        //初始化按钮
        initButton(obj){
            //如果按钮
            if(obj!=null){
                this.buttonDef = obj;
            }
        },
        onParamSelectChange(selectedRowKeys, selectedRows){
            this.paramSelectedRowKeys = selectedRowKeys;
            this.paramSelectedRows = selectedRows
        },
        //添加编辑按钮
        addButton() {
            let btn={
                name:"",
                isPreDef:false,
                type:"custom",
                method:"",
                config:"",
                needConfig:false,
                conditionConfig:'',
                preCondConfig:'',
            }
            btn.idx_=Util.randomId();
            this.buttonDef.push(btn);
        },
        //删除行编辑按钮
        deleteButton(){
            this.removeRows(this.buttonDef,this.buttonSelectedRowKeys)
        },
        //向上移动
        moveBtnUp(){
            this.toUp(this.buttonDef,this.buttonSelectedRowKeys)
        },
        //  向下移动
        moveBtnDown(){
            this.toDown(this.buttonDef,this.buttonSelectedRowKeys)
        },
        onButtonSelectChange(selectedRowKeys, selectedRows){
            this.buttonSelectedRowKeys = selectedRowKeys;
            this.buttonSelectedRows = selectedRows
        },
        changeBtnType(record){
            let aryType=this.buttonTypes.filter(item=>{
                return item.type==record.type;
            });
            let btnType=aryType[0];
            Object.assign(record,btnType);
        },
        /**
         * 配置按钮。
         * @param record
         */
        handleConfig(record){
            let key="func_" + record.method;
            if(this[key]){
                this[key](record);
            }
            else{
                alert(this.i18n('form.method','请编写对应的配置方法') +record.method)
            }
        },
        func_openForm(record){
            //主表字段
            var mainFieldsMap=[];
            var attrList = this.boEnt.boAttrList;
            for (var i = 0; i < attrList.length; i++) {
                if(attrList[i].group){
                    for (var j = 0; j < attrList[i].list.length; j++) {
                        mainFieldsMap.push({
                            label: attrList[i].list[j].comment,
                            key: attrList[i].list[j].name,
                            isSingle:attrList[i].list[j].isSingle
                        })
                    }
                }else {
                    mainFieldsMap.push({
                        label: attrList[i].comment,
                        key: attrList[i].name,
                        isSingle:attrList[i].isSingle
                    })
                }
            }
            //子表字段
            let subFieldsMap=[];
            if(this.boEnt.childrens){
                let childrens=this.boEnt.childrens;
                for (let i = 0; i < childrens.length; i++) {
                    let obj={};
                    let children=childrens[i];
                    obj.alias=children.alias;
                    obj.name=children.name;
                    obj.type=children.boRelation.type
                    obj.fields = children.boAttrList.map(function (item) {
                        return {
                            label: item.comment,
                            key: item.name,
                            isSingle:item.isSingle
                        }
                    });
                    subFieldsMap.push(obj);
                }
            }
            let self = this;
            Util.open({
                component: FormMobileSetting,
                curVm: this,
                widthHeight: ['1200px', '750px'],
                title: self.i18n('form.openForm','配置打开表单'),
                data: {
                    setting: record.setting,
                    originalMainFields:mainFieldsMap,
                    originalSubFields:subFieldsMap
                }
            }, function (action, formSetting) {
                if (action == 'ok') {
                    record.setting = formSetting;
                }
            })
        }
    },
    watch:{
        buttonDef(newVal){
            for(let btn of newVal){
                //给默认存在的按钮添加多语言字段
                this.loadInitBtnI18nVal(btn,'name');
                this.setOtherDefaultI18nVal(btn);
            }
        }
    }
}

</script>

<style scoped>
.editButton{
    padding-top: 10px;
    padding-right: 10px;
    text-align: right;
}
</style>